package com.CTAtracker.android.Activities;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.CTAtracker.android.R;
import com.CTAtracker.android.DAO.FavoriteDataSource;
import com.CTAtracker.android.Fragments.FavoritesFragment;
import com.CTAtracker.android.Fragments.SearchLineFragment;
import com.CTAtracker.android.Fragments.SlidingMenuFragment;
import com.slidingmenu.lib.SlidingMenu;

/**
 * This class is the point of entry of the application. 
 * It handles the sliding action of the menu 
 */
public class SlidingActivity extends Activity {
	/**
	 * The sliding menu
	 */
	protected SlidingMenu _slidingMenu;

	private FavoriteDataSource _favoriteDataSource;

	/**
	 * This method is called when the activity is created.
	 * This method set up the action and the sliding menu.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Inflate Menu
		ActionBar actionbar = getActionBar();
		actionbar.setDisplayShowTitleEnabled(false);
		actionbar.setDisplayShowCustomEnabled(true);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setCustomView(R.layout.actionbar);

		_favoriteDataSource = new FavoriteDataSource(this);

		ImageView menu_button = (ImageView) findViewById(R.id.menu_button);
		menu_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				toggleSlidingMenu();
			}
		});

		// Init the slidingmenu, active on the full screen
		_slidingMenu = new SlidingMenu(this);
		_slidingMenu.setMode(SlidingMenu.LEFT);
		_slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		_slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);

		// Set the frame for the sliding menu and some UI stuff
		_slidingMenu.setMenu(R.layout.sliding_menu_frame);
		_slidingMenu.setShadowDrawable(R.drawable.sliding_menu_shadow);
		_slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
		_slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);

		// Replace the LeftFrame with the SlidingMenuFragment fragment
		getFragmentManager()
		.beginTransaction()
		.replace(R.id.sliding_menu_frame, new SlidingMenuFragment())
		.commit();
		// replace the content with the Around fragment

		_favoriteDataSource.open();
		if (_favoriteDataSource.getAllFavoriteStops().size()!=0){
			this.replaceContent(new FavoritesFragment());
		}else {
			this.replaceContent(new SearchLineFragment());
		}
		_favoriteDataSource.close();	
	}

/**
 * This method replace the current fragment
 * @param frag the new fragment
 */
public void replaceContent(Fragment frag) {
	getFragmentManager()
	.beginTransaction()
	.replace(R.id.content_frame, frag)
	.commit();
}

/**
 * This method triggers the toggle action of the sliding menu 
 */
public void toggleSlidingMenu() {
	_slidingMenu.toggle(true);
}	

}
